#include "Socket.hpp"

using namespace SocketModule;

using ioservice_t = std::function<void(std::unique_ptr<Socket>&, InitAddr&)>;

class TcpServer
{
public:
    TcpServer(int port)
        : _port(port), _listensocket(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listensocket->BuildListenSocket();
    }

    void Start(ioservice_t ioservice)
    {
        _service = ioservice;
        _isrunning = true;
        while (_isrunning)
        {
            
            InitAddr Client;
            std::unique_ptr<Socket> tpst = _listensocket->Accept(Client);
            std::cout << "Server is running..." << std::endl;
            pid_t id = fork();
            if (fork == 0)
            {
                _listensocket->Close();
                _service(tpst, Client);
                exit(OK);
            }
            else
            {
                tpst->Close();
                waitpid(id, nullptr, 0);
            }
        }
        _isrunning = false;
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocket;
    ioservice_t _service;
    bool _isrunning;
};